/*********************SETTER GETTER***********************************/
//set room yang lagi dibuka
function setroomdibukasaatini(namaroom)
{
    document.getElementById("roomdibukasaatini").value = namaroom;
}
//get room yang lagi dibuka
function getroomdibukasaatini()
{
    return document.getElementById("roomdibukasaatini").value;
}


/*********************manipulasi room (yang bagian atas)***********************************/
function showChatSubmit()
{
    document.getElementById('chatinput').style.visibility = 'visible';
}

function hideChatSubmit()
{
    document.getElementById('chatinput').style.visibility = 'hidden'; 
}

function hideOfflineFriend()
{
    my_var = document.getElementById('offlinelist').style.visibility
    if (my_var == 'hidden')
        {document.getElementById('offlinelist').style.visibility = 'visible';}
    else
        {document.getElementById('offlinelist').style.visibility = 'hidden';}
}

function addopenedroom(namaroom, javascript)
{
    if (document.getElementById('Room'+namaroom)==null)
    {
        var container = document.getElementById('roomdibuka');
        var new_element = document.createElement('li');
        new_element.id="room"+namaroom;
        new_element.innerHTML = '<a id="Room'+namaroom+'" onclick="'+javascript+'" >'+namaroom+'</a>';
        container.appendChild(new_element);
    }
}

function delopenedroom(namaroom)
{
    var container = document.getElementById('roomdibuka');
    var del_element = document.getElementById('Room'+namaroom);
    
    container.removeChild(del_element);
}

function clearopenedroom()
{
    document.getElementById('roomdibuka').innerHTML="";
}

//clear list user diinterface
function clearRoomUser() {
    document.getElementById("chatlist").innerHTML="";
}

//clear list user diinterface
function clearChatHTML() {
    document.getElementById("isiChatting").innerHTML="";
}

/************************************AJAX Request element****************************************/
//ajaxnya untuk request segala sesuatu ke servlet
var ajaxRequest1;  // The variable that makes Ajax possible!
function ajaxFunction1(url, cfunc){
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest1 = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest1 = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest1 = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequest1.onreadystatechange = cfunc;
    ajaxRequest1.open("GET", url, true);
    ajaxRequest1.send();
}

//ajaxnya hanya untuk nampilin chat
var ajaxRequestisichat;  // The variable that makes Ajax possible!
function ajaxFunctionisichat(url, cfunc){
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequestisichat = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequestisichat = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequestisichat = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequestisichat.onreadystatechange = cfunc;
    ajaxRequestisichat.open("GET", url, true);
    ajaxRequestisichat.send();
}

//ajaxnya hanya untuk list user di suatu room
var ajaxRequestisicategory;  // The variable that makes Ajax possible!
function ajaxFunctionisicategory(url, cfunc){
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequestisicategory = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequestisicategory = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequestisicategory = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequestisicategory.onreadystatechange = cfunc;
    ajaxRequestisicategory.open("GET", url, true);
    ajaxRequestisicategory.send();
}

//ajaxnya hanya untuk ngatur chat window secara integrated
var ajaxRequestchatwithother;  // The variable that makes Ajax possible!
function ajaxFunctionchatwithother(url, cfunc){
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequestchatwithother = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequestchatwithother = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequestchatwithother = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequestchatwithother.onreadystatechange = cfunc;
    ajaxRequestchatwithother.open("GET", url, true);
    ajaxRequestchatwithother.send();
}

/************************************AJAX elementer****************************************/
//ambil tulisan chat yang room name nya tertentu dan tampilkan ke chat board
function ajaxshowisiRoomChat(room) {
    ajaxFunctionisichat("ChatProcess?Action=showRoom&Room=" + room , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestisichat.readyState == 4){
            document.getElementById("isiChatting").innerHTML=ajaxRequestisichat.responseText;
            setroomdibukasaatini(room);

        }
    });
}

//add emty room ke list of room global
function ajaxaddEmptyRoomChat(room, parentCategory) {
    ajaxFunction1("ChatProcess?Action=addEmptyRoom&Room=" + room +"&parentCategory="+parentCategory , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequest1.readyState == 4){
    }
    });
}

//add user ke room
function ajaxaddRoomUser(room, username,connectedFrom,role) {
    ajaxFunction1("ChatProcess?Action=addRoomUser&Room=" + room +"&username="+username+"&connectedFrom="+connectedFrom+"&role="+role , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequest1.readyState == 4){
    }
    });
}

//show user didalam room
function ajaxshowRoomUser(room) {
    ajaxFunctionisicategory("ChatProcess?Action=ajaxshowRoomUser&Room=" + room , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestisicategory.readyState == 4){
            document.getElementById("chatlist").innerHTML=ajaxRequestisicategory.responseText;
        }
    });
}




function parseMessage(message) {
    var action = "";
    var parameter = "";
    var Role = document.getElementById('role').value;
    var ganteng = true;
    for (var i = 1; i < message.length; ++i) {
        if (message[i] == " " && ganteng) {
            ganteng = false;
            continue;
        }
        if (ganteng)
            action = action + message[i];
        else
            parameter = parameter + message[i];
    }
    if (Role == 1)
    {
        switch (action) {
            case "create" :
                var explode = parameter.split(' ');
                ajaxaddEmptyRoomChat(explode[0], explode[1]); //sementara 1 dulu, nanti isi dengan category yang tepat
                ajaxshowRoomUser(parameter);
                break;
            case "join" :
                chatWithRoom(document.getElementById('username').value,parameter);
                break;
            case "chat" :
                chatWithOtherUser(document.getElementById('username').value,parameter);
                break;
            case "addfriend" :
                ajaxaddFriend(document.getElementById('username').value,parameter);
                break;
            case "exit" :
                keluardariRoom(getroomdibukasaatini(),document.getElementById('username').value);
                break;
            case "info" :
                if (parameter=='') //kalau param kosong maka rooom saat ini yang diinfokan
                {
                    ajaxinfo(getroomdibukasaatini());
                }
                else
                {
                    ajaxinfo(parameter);
                }

                break;

            case "addbot" :
                if (parameter=="1")
                {
                    statusbot1=true;
                }
                else if (parameter=="2")
                {
                    statusbot2=true;
                }

                break;
            case "rmbot" :
                if (parameter=="1")
                {
                    statusbot1=false;
                }
                else if (parameter=="2")
                {
                    statusbot2=false;
                }
                break;
            default :
                alert ("Fungsi nya ga ada gan!");
                break;
        }
    }
    else if (Role == 2)
    {
        switch (action) {
            case "create" :
                var explode = parameter.split(' ');
                ajaxaddEmptyRoomChat(explode[0], explode[1]); //sementara 1 dulu, nanti isi dengan category yang tepat
                ajaxshowRoomUser(parameter);
                break;
            case "join" :
                chatWithRoom(document.getElementById('username').value,parameter);
                break;
            case "chat" :
                chatWithOtherUser(document.getElementById('username').value,parameter);
                break;
            case "addfriend" :
                ajaxaddFriend(document.getElementById('username').value,parameter);
                break;
            case "exit" :
                keluardariRoom(getroomdibukasaatini(),document.getElementById('username').value);
                break;
            case "info" :
                if (parameter=='') //kalau param kosong maka rooom saat ini yang diinfokan
                {
                    ajaxinfo(getroomdibukasaatini());
                }
                else
                {
                    ajaxinfo(parameter);
                }

                break;
            case "kick" :
                keluardariRoom(getroomdibukasaatini(), parameter);
                break;

            case "ban" :
                addUserToBan(parameter, getroomdibukasaatini());
                break;

            case "unban" :
                delUserFromBan(parameter, getroomdibukasaatini());
                break;

            case "persist" :
                if (parameter == 'on')
                {
                    setPersist(getroomdibukasaatini(), true);
                }
                else if (parameter == 'off')
                {
                    setPersist(getroomdibukasaatini(), false);
                }

                break;

            case "setowner" :
                setOwner(getroomdibukasaatini(), parameter);
                break;

            case "addbot" :
                if (parameter=="1")
                {
                    statusbot1=true;
                }
                else if (parameter=="2")
                {
                    statusbot2=true;
                }

                break;
            case "rmbot" :
                if (parameter=="1")
                {
                    statusbot1=false;
                }
                else if (parameter=="2")
                {
                    statusbot2=false;
                }
                break;
            default :
                alert ("Fungsi nya ga ada gan!");
                break;
        }
    }
    
    
}
function chatCommand_join(parameter) {
    return parameter;
}

function chatCommand_chat(parameter) {
    return parameter;
}

function chatCommand_addfriend(parameter) {
    return parameter;
}

function chatCommand_exit(parameter) {
    return parameter;
}

function chatCommand_info(parameter) {
    return parameter;
}

function chatCommand_kick(parameter) {
    return parameter;
}

function chatCommand_ban(parameter) {
    return parameter;
}

function chatCommand_unban(parameter) {
    return parameter;
}

function chatCommand_persist(parameter) {
    return parameter;
}

function chatCommand_setowner(parameter) {
    return parameter;
}

function chatCommand_addbot(parameter) {
    return parameter;
}

function chatCommand_rmbot(parameter) {
    return parameter;
}
/// TODO : masukin fungsi2 ke javascript ini
function chatCommand_create(parameter) {
    return parameter;
}

//add friend
function ajaxaddFriend(username, friend) {
ajaxFunction1("ChatProcess?Action=addFriend&friend=" + friend +"&username="+username , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequest1.readyState == 4){
            
        }

    });    
}

var statusbot1 = false; //mati awalnya
var statusbot2 = false;

//add message user ke room tertentu
function ajaxaddRoomUserMessage(room, username, message) {
    if (message[0] == '/') {
        parseMessage(message)
    } else {
        //alert(message);
        

        if((message=="hai")&&(statusbot1))
        {
            alert("hai juga say muach muach :* ");
        }
        else if ((message=="darwin")&&(statusbot2))
        {
            alert("darwin... jangan makan gua T___T   :v o o o o o (Aaargh)> O+<  ");
        }

        else
            ajaxFunction1("ChatProcess?Action=addRoomUserMessage&Room=" + room +"&username="+username+"&message="+message , function()
            {
                // Create a function that will receive data sent from the server
                if(ajaxRequest1.readyState == 4){
            }
            });
    }
}

//add user ke room
function ajaxinfo(yangdicari) {
    ajaxFunction1("ChatProcess?Action=userInfo&yangdicari=" + yangdicari , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequest1.readyState == 4){
            alert(ajaxRequest1.responseText);
        }
    
    });
}


//show list room category id tertentu di list of category belum tahu akan ditaruh dimana
function ajaxshowRoomCategory(room, ParentcategoryID) {
    ajaxFunctionisicategory("ChatProcess?Action=showRoomCategory&Room=" + room+"&ParentcategoryID="+ParentcategoryID  , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestisicategory.readyState == 4){
    }
    });
}

//nambah window yang terbuka (belumbisa diklik harus ditambah onclick event)
function chatWithOtherUser(myusername, partnerusername)
{
    ajaxFunctionchatwithother("ChatProcess?Action=chatWithOtherUser&myusername=" + myusername+"&partnerusername="+partnerusername , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestchatwithother.readyState == 4){
            var javascript="ajaxshowisiRoomChat('"+myusername+partnerusername+"');clearRoomUser();showChatSubmit();"  ;
            addopenedroom(partnerusername,javascript);
            ajaxshowisiRoomChat(myusername+partnerusername);
            clearRoomUser();
            showChatSubmit();
        }
    });
}


//nambah window room yang terbuka yang merupakan room
function chatWithRoom(username,room)
{
    ajaxFunctionchatwithother("ChatProcess?Action=chatWithRoom&myusername=" + username+"&room="+room , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestchatwithother.readyState == 4){
            var javascript="ajaxshowisiRoomChat('"+room+"');ajaxshowRoomUser('"+room+"');"  ;
            addopenedroom(room,javascript);
            ajaxshowisiRoomChat(room);
            ajaxshowRoomUser(room);
            showChatSubmit();
        }
    });
}



//keluar dari room yang sudah dibuka saat ini
function keluardariRoom(roomname,myusername)
{
    ajaxFunctionchatwithother("ChatProcess?Action=keluarroom&myusername=" + myusername+"&roomname="+roomname , function()
    {
        // Create a function that will receive data sent from the server
        if(ajaxRequestchatwithother.readyState == 4){
            delopenedroom(roomname);
            setroomdibukasaatini("");
            refresh();
            clearRoomUser();
            clearChatHTML();
            hideChatSubmit();
        }
    });
}

function addUserToBan(Username, Room)
{
    ajaxFunction1("ChatProcess?Action=addUserToBan&Username=" + Username + "&Room=" + Room, function ()
    {
        if(ajaxRequest1.readyState == 4){
            
        }
    });
}

function delUserFromBan(Username, Room)
{
    ajaxFunction1("ChatProcess?Action=delUserFromBan&Username=" + Username + "&Room=" + Room, function ()
    {
        if(ajaxRequest1.readyState == 4){

        }
    });
}

function setPersist(Room, State)
{
    ajaxFunction1("ChatProcess?Action=setPersist&Room=" + Room + "&State=" + State, function ()
    {
        if(ajaxRequest1.readyState == 4){

        }
    });
}

function setOwner(Room, Owner)
{
    ajaxFunction1("ChatProcess?Action=setPersist&Room=" + Room + "&Owner=" + Owner, function ()
    {
        if(ajaxRequest1.readyState == 4){
        
        }
    });
}

//show list room category id tertentu di list of category belum tahu akan ditaruh dimana
function showRoomCategorydiaddroom(ParentcategoryID)
{
    my_var = document.getElementById('room' + ParentcategoryID).style.visibility
    if (my_var == 'hidden')
        {document.getElementById('room' + ParentcategoryID).style.visibility = 'visible';}
    else
        {document.getElementById('room' + ParentcategoryID).style.visibility = 'hidden';}
}

function refresh()
{
    ajaxshowisiRoomChat(getroomdibukasaatini());
}

function getroomdenganusertertentudidalamnya()
{
    

}

/*DEBUGGING*/
function isidummy()
{
    ajaxaddEmptyRoomChat("cobaroom1","1");
    ajaxaddEmptyRoomChat("cobaroom2","1");
    ajaxaddRoomUser("cobaroom2","archie","127.0.0.1","1");
    ajaxaddRoomUser("cobaroom2","dawn","127.0.0.1","1");
    ajaxaddRoomUserMessage("cobaroom2","dawn","hai");
    ajaxaddRoomUserMessage("cobaroom2","archie","hai juga");
}
function showisi()
{
    ajaxshowisiRoomChat("cobaroom2");
    ajaxshowRoomUser("cobaroom2");
}